﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Krile.Imported.Snippets
{
    public static class WindowSystem
    {

        [DllImport("user32.dll")]
        extern static IntPtr GetWindow(IntPtr hWnd, uint uCmd);

        [DllImport("user32.dll")]
        extern static IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        extern static bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// Compares Z order
        /// </summary>
        /// <param name="x">window x</param>
        /// <param name="y">window y</param>
        /// <returns>If x before y, it return negative value.</returns>
        public static int CompareZOrder(HandleRef x, HandleRef y)
        {
            if (x.Handle == y.Handle)
                return 0;
            IntPtr hWnd = x.Handle;
            while (hWnd != IntPtr.Zero)
            {
                if (hWnd == y.Handle)
                    return -1;
                hWnd = GetWindow(hWnd, (uint)HwndSearchType.GW_HWNDNEXT);
            }
            return 1;
        }

        public enum HwndSearchType
        {
            /// <summary>
            /// 最前面のウィンドウを探す
            /// </summary>
            GW_HWNDFIRST = 0,
            /// <summary>
            ///最背面のウィンドウを探す
            /// </summary>
            GW_HWNDLAST = 1,
            /// <summary>
            ///すぐ背面のウィンドウを探す
            /// </summary>
            GW_HWNDNEXT = 2,
            /// <summary>
            ///すぐ前面のウィンドウを探す
            /// </summary>
            GW_HWNDPREV = 3,
            /// <summary>
            ///オーナーウィンドウを探す
            /// </summary>
            GW_OWNER = 4,
            /// <summary>
            ///トップレベル子ウィンドウを探す
            /// </summary>
            GW_CHILD = 5
        };

        public static IntPtr GetWindow(HandleRef hwnd, HwndSearchType searchType)
        {
            return GetWindow(hwnd.Handle, (uint)searchType);
        }

        public static void SetForeground(Form f)
        {
            SetForegroundWindow(f.Handle);
        }
    }
}